package com.yunhe.authority.controller.company;

import com.alibaba.excel.EasyExcel;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.yunhe.authority.domain.company.Company;
import com.yunhe.authority.listener.NewUploadDataListener;
import com.yunhe.authority.listener.UploadDataListener;
import com.yunhe.authority.model.CompanyUpload;
import com.yunhe.authority.model.OfficeManageCompanyInfoVO;
import com.yunhe.authority.model.poi.CompanyPoi;
import com.yunhe.authority.util.MyHeaderUtil;
import com.yunhe.common.annotation.OperationRecord;
import com.yunhe.common.constant.SystemConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ModelNotFoundException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.model.ResultObject;
import com.yunhe.authority.service.company.CompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Api(value = "company", description = "企业维护", tags = {"Model_Company"})
@RequestMapping("/companys")
@RestController
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MyHeaderUtil headerUtil;

    @ApiOperation("根据企业ID获得企业")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "企业ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<ResultObject<Company>> getById(@PathVariable("id") Long id) throws ObjectNotFoundException {
        Company company = companyService.findById(id);
        return new ResponseEntity<>(new ResultObject<>(company), HttpStatus.OK);
    }

    /**
     * 新增企业
     * @param realStationId 真实园区
     * @param company 企业对象
     */
    @ApiOperation("新增企业")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realStationId", value = "真实园区id", required = true, dataType = "long", paramType = "query")
    })
    @RequestMapping(method = RequestMethod.POST)
    @OperationRecord(menu = "企业信息", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> post(@RequestBody Company company,
                                             @RequestParam("realStationId") Long realStationId)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException, PinyinException, ModelNotFoundException {
        Company newCompany = companyService.createCompany(company, realStationId);
        return new ResponseEntity<>(new ResultObject<>(newCompany), HttpStatus.OK);
    }

    /**
     * 删除企业
     * @param ids
     */
    @ApiOperation("删除企业")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "企业ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @OperationRecord(menu = "企业信息", actionType = SystemConsts.ACTION.DELETE)
    public ResponseEntity<ResultObject> delete(@PathVariable("ids") String ids) throws ObjectNotFoundException, ModelNotFoundException, ArgumentErrorException, UniqueConstraintsException {
        companyService.deleteCompany(ids);
        return new ResponseEntity<>(new ResultObject<>("success"), HttpStatus.OK);
    }

    /**
     * 更新企业（更新全部字段）
     * @param id
     * @param company
     */
    @ApiOperation("更新企业")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @OperationRecord(menu = "企业信息", actionType = SystemConsts.ACTION.EDIT)
    public ResponseEntity<ResultObject> put(@PathVariable("id") Long id,
                                            @RequestBody Company company)
            throws ArgumentErrorException,  UniqueConstraintsException, ObjectNotFoundException {
        company.setId(id);
        Company newCompany = companyService.updateCompany(company);
        return new ResponseEntity<>(new ResultObject<>(newCompany), HttpStatus.OK);
    }

    @ApiOperation("根据统一社会信用代码获得企业")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unifiedSocialCreditCode", value = "统一社会信用代码", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/byUnifiedSocialCreditCode" , method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getByUnifiedSocialCreditCode(@RequestParam("unifiedSocialCreditCode") String unifiedSocialCreditCode) {
        Company company = companyService.findByUnifiedSocialCreditCode(unifiedSocialCreditCode);
        return new ResponseEntity<>(new ResultObject<>(company), HttpStatus.OK);
    }

    @ApiOperation("在园项目分页查询")
    @RequestMapping(value = "/all" , method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getAllForPage(@ModelAttribute PageParam pageParam) {
        Page<CompanyUpload> company = companyService.findAllForPage(pageParam);
        return new ResponseEntity<>(new ResultObject<>(company), HttpStatus.OK);
    }

    @ApiOperation("根据园区id查询在园项目分页查询")
    @RequestMapping(value = "/searchStationAllCompany/{stationId}" , method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getAllForPageByStationId(@ModelAttribute PageParam pageParam,
                                                                 @RequestParam(value = "keyWords", required = false) String keyWords,
                                                                 @PathVariable(value = "stationId") Long stationId) {
        Page<Company> company = companyService.findStationAllCompanyForPage(keyWords, stationId, pageParam);
        return new ResponseEntity<>(new ResultObject<>(company), HttpStatus.OK);
    }


    @ApiOperation("根据园区id查询在园企业")
    @RequestMapping(value = "/findCompanyByRealStationId" , method = RequestMethod.GET)
    public ResponseEntity<ResultObject<List<Company>>> findCompanyByRealStationId(@RequestParam(value = "stationId",required = true) Long stationId) {
        List<Company> companys = companyService.findCompanyByRealStationId(stationId);
        return new ResponseEntity<>(new ResultObject<>(companys), HttpStatus.OK);
    }

    @ApiOperation("在园项目模板导入")
    @RequestMapping(value = "/upload" , method = RequestMethod.POST)
    @OperationRecord(menu = "在园项目有管理", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> upload(@RequestBody MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), CompanyUpload.class, new UploadDataListener(companyService)).sheet().doRead();
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    @ApiOperation("数据导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "在园项目id，用“，”隔开", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/export")
    @OperationRecord(menu = "在园项目管理", actionType = SystemConsts.ACTION.EXPORT)
    public ResponseEntity<ResultObject> export(@RequestParam("ids") String ids,
                                               HttpServletResponse httpServletResponse
                                               ) throws ArgumentErrorException, UniqueConstraintsException {
        Long exportPeopleId = headerUtil.getHeaderUserId();
        if(exportPeopleId == null){
            throw new ArgumentErrorException("未获取到登录信息，请重新登录！");
        }
        companyService.export(ids ,exportPeopleId , httpServletResponse);
        return null;
    }

    @ApiOperation("在园项目模板导入new")
    @RequestMapping(value = "/uploadNew" , method = RequestMethod.POST)
//    @OperationRecord(menu = "在园项目有管理", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> uploadNew(@RequestBody MultipartFile file) throws Exception {
//        companyService.importCompanyExcel(file);
        EasyExcel.read(file.getInputStream(), CompanyPoi.class, new NewUploadDataListener(companyService)).sheet().doRead();
        return new ResponseEntity<>(new ResultObject<>("success"), HttpStatus.OK);
    }

    @ApiOperation("数据导出new")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "在园项目id，用“，”隔开", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/exportNew")
//    @OperationRecord(menu = "在园项目管理", actionType = SystemConsts.ACTION.EXPORT)
    public ResponseEntity<ResultObject> exportNew(@RequestParam("ids") String ids,
                                               HttpServletResponse httpServletResponse
    ) throws ObjectNotFoundException {
        companyService.exportNew(ids , httpServletResponse);
        return new ResponseEntity<>(new ResultObject<>("success"), HttpStatus.OK);
    }

    /**
     * #########################################################################################################################################################
     */
    @ApiOperation("企业基础信息导入模板下载")
    @GetMapping("/downCompanyUploadTemplate")
    public ResponseEntity<ResultObject> downCompanyUploadTemplate(HttpServletResponse httpServletResponse) throws ArgumentErrorException, IOException, InvalidFormatException {
//        Long exportPeopleId = headerUtil.getHeaderUserId();
//        if(exportPeopleId == null){
//            throw new ArgumentErrorException("未获取到登录信息，请重新登录！");
//        }
        companyService.downCompanyUploadTemplate(null,httpServletResponse);
        return null;
    }


    @ApiOperation("企业离园")
    @RequestMapping(value = "/companyLeave" , method = RequestMethod.POST)
    public ResponseEntity<ResultObject> companyLeave(@RequestParam(value = "companyId", required = true) Long companyId) throws ArgumentErrorException, ObjectNotFoundException, ModelNotFoundException, UniqueConstraintsException {
        companyService.companyLeave(companyId);
        return new ResponseEntity<>(new ResultObject<>("success"), HttpStatus.OK);
    }

    @ApiOperation("房源管理查看企业信息")
    @RequestMapping(value = "/getCompanyInfoByOfficeId", method = RequestMethod.GET)
    public ResponseEntity<ResultObject<OfficeManageCompanyInfoVO>> getCompanyInfoByOfficeId(@RequestParam("officeId") Long officeId){
        OfficeManageCompanyInfoVO officeManageCompanyInfoVO = companyService.getCompanyInfoByOfficeId(officeId);
        return new ResponseEntity<>(new ResultObject<>(officeManageCompanyInfoVO), HttpStatus.OK);
    }
}
